<?php 
class CLoginController extends CController{

	public function __construct() {
		parent::__construct();
		return true;
	}
	
	public function initialize() {
		parent::initialize();
				
		if( true == isset( $_SESSION['user_id'] ) && false == isset( $_REQUEST['action'] ) ) {
			header( 'location:' . SITE_PATH . '/admin' );
			exit;
		} 
		
		return true;
	}
	
	public function execute() {		
		
		switch( $this->m_strAction ) {
			
			case NULL:			
			case 'login':
				$this->handleViewLogin();
				break;
				
			case 'do_login':
				$this->handleDoLogin();
				break;
			
			case 'logout':
				$this->handleDoLogOut();
			break;
			default:
				// Empty default case
				
		}
	}
	
	public function handleViewLogin() {	
		$this->displayLogin();
	}
	
	public function handleDoLogin() {

		$strUserName = $_REQUEST['login_name'];
		$strPassword = md5( $_REQUEST['password'] );
		
		$objUser = CUsers::fetchUserByUserNameByPassword( $strUserName, $strPassword, $this->m_objDatabase );
		
		if( true == valObj( $objUser, 'CUser' ) ) {
			$_SESSION[SITE_TITLE]['login_user_id'] = $objUser->getId();
			header( 'location:' . SITE_PATH . '/admin' );
			exit;
		}
		
		
	}
	
	public function handleDoLogOut() {
		
		unset( $_SESSION[SITE_TITLE] );
		$_SESSION[SITE_TITLE] = NULL;
		
		header( 'location:' . SITE_PATH . '/admin/login' );
		exit;
	}
	
	public function displayLogin() {
		parent::display();
		$this->m_objSmarty->display( TEMPLATE_DIR_PATH . '/admin/login/view_login.tpl');
	
	}

}
?>